import React, { useState } from 'react';
import PropTypes from 'prop-types';
import _, { get } from 'lodash';
import { Radio, Select, Tooltip, Icon } from 'antd';
import CheckboxSelect from '@components/checkbox-select';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions as assetManageActions } from '@containers/asset-manage/reducer';

const VulStrategy = props => {
  const [strategy, setStrategy] = useState('affectedComponent');
  const [errorMsg, setErrorMsg] = useState('');
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [selectedOnedays, setSelectedOnedays] = useState([]);

  const { user, changeCallback, templates, onedays } = props;
  const showJump = _.get(user, 'role') === 'operator' || _.get(user, 'is_admin', false);

  const handleChangeCallback = query => {
    const strategyMap = { detectionPolicy: strategy, ...query };
    changeCallback(strategyMap);
  };

  const onChangeTemplate = checkedTemplateId => {
    setSelectedTemplateId(checkedTemplateId);
    setErrorMsg('');
    handleChangeCallback({ templateId: checkedTemplateId });
  };

  const onStrategyChange = e => {
    const strategy = e.target.value;
    setStrategy(strategy);
    setErrorMsg('');
    handleChangeCallback({ detectionPolicy: strategy });
  };

  const onSelectOnedays = keys => {
    let error = '';
    if (!keys.length) {
      error = '插件选择不能为空';
    }
    setSelectedOnedays(keys);
    setErrorMsg(error);
    handleChangeCallback({ onedayIdList: keys });
  };

  return (
    <div className={'vul-strategy-item'}>
      <div className={'vul-strategy-item-sub-title'}>
        检测策略&nbsp;
        <Tooltip
          title={
            <div>
              选择受影响插件：针对探测出存活资产的指纹信息自动筛选受影响插件进行漏洞普查；
              <br />
              选择模板：针对探测出的存活资产进行所选模板的漏洞普查；
              <br />
              选择自定义：针对探测出的存活资产进行所勾选插件的漏洞普查。
            </div>
          }
        >
          <Icon type="exclamation-circle" />
        </Tooltip>
      </div>
      <div className={'vul-strategy-item-template'}>
        <div className={'vul-strategy-item-template-radio'}>
          <Radio.Group value={strategy} onChange={onStrategyChange}>
            <Radio value="affectedComponent">受影响插件</Radio>
            <Radio value="template">模板</Radio>
            <Radio value="custom">自定义</Radio>
          </Radio.Group>
        </div>
        {strategy === 'template' ? (
          <Select
            value={selectedTemplateId}
            onChange={onChangeTemplate}
            className="template-selects"
            placeholder="选择漏洞策略模板"
            style={{ width: '100%' }}
          >
            {templates.map(({ name, _id }) => (
              <Select.Option key={_id} value={_id}>
                {name}
              </Select.Option>
            ))}
          </Select>
        ) : strategy === 'custom' ? (
          <CheckboxSelect
            className="plugins"
            placeholder="请输入插件名称进行搜索"
            options={onedays}
            selected={selectedOnedays}
            onChange={onSelectOnedays}
            allButton={false}
          />
        ) : null}
        {strategy === 'template' && showJump && (
          <Link
            to="/asset-config/strategy-template"
            style={{ display: 'block', marginTop: 8 }}
            target="_blank"
          >
            配置漏洞策略模板
          </Link>
        )}
        {errorMsg && <p className={'vul-strategy-item-template-validate-error'}>{errorMsg}</p>}
      </div>
    </div>
  );
};

VulStrategy.propTypes = {
  user: PropTypes.object,
  changeCallback: PropTypes.func,
  templates: PropTypes.array,
  onedays: PropTypes.array
};

const mapStateToProps = state => {
  return {
    user: get(state, 'auth.user', {}),
    templates: get(state, 'assetManage.templates', []),
    onedays: get(state, 'assetManage.onedays', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(VulStrategy);
